<template>
	<view class="main-content">
		<view class="main-body" v-if="tabValue == 0">
			<view class="icon-block mt-20">
			  <view class="msg">
				<u-avatar
					v-if="user.avatar"
					:src="user.avatar"
					shape="circle"
					size="45"
					bgColor="#0087FC">
				</u-avatar>
				<u-avatar
					v-else
					:text="user.userName ? user.userName.slice(1) :''"
					:fontSize="user.userName && user.userName.length > 2?15:20"
					shape="circle"
					size="45"
					bgColor="#0087FC">
				</u-avatar>
			    <view class="msg-body">
			      <view class="msg-body__header">
			        <view>{{ user.userName }}</view>
			      </view>
			      <view class="msg-body__content">
					<text class="msg-body__content_userText">{{ user.dept.deptName }}</text> 
				  </view>
			    </view>
			  </view>
			</view>
			
			<view class="icon-dk mt-20">
			  <view class="icon-list">
			  	<view class="icon-item">
			  	  <view class="msg-title">上班{{ beginWorkTime }}</view>	
					<view class="msg-body__content_text" v-show="!isBeginDk">未打卡</view>
					<view class="msg-body__content" v-show="isBeginDk">
						<u-icon name="checkmark-circle-fill" color="#2979ff" customStyle="font-size:36rpx;line-height:36rpx;"></u-icon>
						<text class="msg-body__content_text">{{ beginDkTime }}已打卡</text> 
						<view class="msg-body__warn" v-show="isLate == '1'">迟到</view>
					</view>
			  	</view>
			  	<view class="icon-item">
					<view class="icon-item_top">
						<view class="msg-title">下班{{ endWorkTime }}</view>
						<text v-show="isEndDk" class="msg-body__content__renew" @click="renewEndTime()">更新打卡</text>
					</view>
					<view class="msg-body__content_text" v-show="!isEndDk">未打卡</view>
				  	<view class="msg-body__content" v-show="isEndDk">
						<u-icon name="checkmark-circle-fill" color="#2979ff" customStyle="font-size:36rpx;line-height:36rpx;"></u-icon>
						<text class="msg-body__content_text">{{ endDkTime }}已打卡</text>	
						<view class="msg-body__warn" v-show="isLeave != '0'">早退</view>
					</view>
			  	</view>
			  </view>
			  <!-- 打卡圆圈 -->
			  <view class="circle" 
			  @click="punchIn"
			  >
				  <view class="circle-body" :style="!inRange?'background-color: #01CB8B':''">
					  <view class="circle-body-title" v-show="!isBeginDk">上班打卡</view>
					  <view class="circle-body-title" v-show="isBeginDk">下班打卡</view>
					  <view class="circle-body__content">{{nowTime}}</view>
				  </view>
			  </view>
			  <!-- 未在打卡区域提示 -->
			  <view v-if="!inRange" style="justify-content: center;display: flex;color: rgba(39, 40, 50, 0.6);margin-top: 40rpx;align-items: center;">
				<icon type="warn" size="16"/>
				<text class="circle-content">未进入考勤范围</text>
			  </view>
			  <view v-if="inRange" style="justify-content: center;display: flex;color: rgba(39, 40, 50, 0.6);margin-top: 40rpx;align-items: center;">
				<icon type="success" size="16"/>
				<text class="circle-content">已进入考勤范围：江苏中兴测绘信息有限公司</text>
			  </view>
			</view>
			
			<view>
				<u-action-sheet
				round="10"
				:closeOnClickOverlay="true" 
				:closeOnClickAction="true"
				:title="isBeginDk == false?'迟到打卡备注':'早退打卡备注'" 
				:show="popupShow"
				@close="popupShow=false">
					<u-divider style="margin-top: -10rpx;"></u-divider>
					<view style="margin: 0 25rpx 25rpx 25rpx;text-align: left;">
						<text style="color: #000000;font-size: 32rpx;">备注(选填)</text>
						<u--input
						:placeholder="isBeginDk == false?'请填写迟到原因':'请填写早退原因'"
						border="bottom"
						style="margin-bottom: 30rpx;"
						v-model="lateOrEarlyRemark"
						>
						</u--input>
						<u-button color="#FE8802" :text="isBeginDk == false?'迟到打卡':'早退打卡'" @click="confirmDk()"></u-button>
					</view>
				</u-action-sheet>
			</view>
		</view>
		
		<view  v-else-if="tabValue == 1">
			<kqtj ref="kqtj"></kqtj>
		</view>
		
		<u-tabbar
			:value="tabValue"
			:fixed="true"
			:placeholder="false"
			:safeAreaInsetBottom="false"
		>
			<u-tabbar-item text="打卡" icon="map" @click="clickTab(0)" ></u-tabbar-item>
			<u-tabbar-item text="统计" icon="file-text" @click="clickTab(1)" ></u-tabbar-item>
		</u-tabbar>
		
		<u-toast ref="uToast"></u-toast>
		
		<!-- 弹出层：提示打卡成功 -->
		<clock-success
		:showDkSuc="showDkSuc"
		:beginDkTime="beginDkTime"
		:endDkTime="endDkTime"
		:isBeginDk="isBeginDk"
		:isEndDk="isEndDk"
		v-on:isShow='isShowSuc'
		></clock-success>
		
		<!-- 更新打卡提示 -->
		<view class="">
			<u-modal :show="renewTip" :showCancelButton='true' @cancel="closeRenewTip" @confirm="confirmRenew('renew')">
				<view class="slot-content">
					<text>是否确认将下班打卡时间由「{{ endDkTime }}」更新为当前时间</text>
				</view>
			</u-modal>
		</view>
		
		<!-- 停留时间过久提示框 -->
		<view >
			<u-modal :show="showCloseTime" :confirmText='confirmText' @confirm="closeTimeOut">
				<view class="slot-content">
					<u-icon name="error-circle-fill" color="#f9ae3d" size="28"></u-icon>
					<rich-text class="slot-content__text" :nodes="content"></rich-text>
				</view>
			</u-modal>
		</view>
	</view>
</template>

<script>
	import kqtj from './kqtj.vue'
	import env from '@/env.js'
	import amap from '@/static/js/amap-wx.130.js';
	import { getConfigKey } from '@/api/config'
	import { editDk, getDkInfo } from '@/api/kqdk.js'
	import getDateTime from '@/utils/getdateTime.js'
	import { strFormatHourMSTime } from '@/utils/format.js'
	import clockSuccess from '@/components/clock-success/clock-success.vue'
	import { getDistance, compareTime } from '@/utils/dkTools.js' //一些些工具
	import gcoord from 'gcoord';
	export default {
		components:{ kqtj, clockSuccess },
		data() {
			return {
				locationCount:3,
				bssid: '',
				tabValue: 0,
				user: {},
				nowTime: '',
				timeout: undefined,
				timer: undefined,
				inRange: false, //是否在打卡区域范围
				popupShow: false,
				cdzt: '迟到打卡备注',
				amapPlugin: null,
				gaodekey: env.gaodekey,
				urlStr: '',
				distance: 99999,  //距离
				todayDate: '',  //当天日期
				isBeginDk: false,  //早上是否打卡
				isEndDk: false,  //晚上是否打卡
				dkInfo: '',  //打卡信息
				lateOrEarlyRemark: '',  //迟到原因
				dkInfoId: '',  //打卡id
				showDkSuc: false,  //打卡是否成功(弹出成功弹框)
				beginDkTime: '', //打卡上班时间
				endDkTime: '', //打卡下班时间
				beginWorkTime: '',  //上班时间
				endWorkTime: '',  //下班时间
				renewTip: false,  //更新打卡提示
				isEarly: false,  //是否早退
				isLater: false,  //是否迟到
				isDuanqi: false,  //是否在15s内
				isLate: '0',  //是否迟到
				isLeave: '0',  //是否早退
				xiabanTime: '',  //下半暂存时间
				content: '打卡停留时间过长',
				showCloseTime: false,
				confirmText: '我知道了',
			}
		},
		// onLoad() {
		// 	if (this.hasLogin) {
		// 	  this.user = uni.getStorageSync("user")
		// 	}
		// 	this.startInterval()
		// },
		onLoad() {
			this.amapPlugin = new amap.AMapWX({
				key: this.gaodekey
			});
			var timeStr = getDateTime.dateTimeStr('y-m-d');
			this.todayDate = timeStr 
		},
		onShow() {
			this.user = uni.getStorageSync("loginInfo").user
			console.log('this.user', this.user)
			// #ifdef MP-WEIXIN
			this.getSettingMess()
			// #endif
			// #ifdef APP-PLUS
			this.startInterval()
			// #endif
			let time = setTimeout(item => {
				this.showCloseTime = true
				clearTimeout(time)      
			}, 120000)
		},
		created(){
			this.getTodayDkInfo()
			// this.getPosition()
		},
		onHide() {
			this.closeInterval()
		},
		destroyed() {
			this.closeInterval()
		},
		methods: {
			// 获取当天打卡信息
			async getTodayDkInfo() {
				const { data } = await getDkInfo()
				if( data.code === 200 ) {
					if( data.data ) {
						this.dkInfo = data.data
						this.dkInfoId = this.dkInfo.id
						this.beginWorkTime = this.dkInfo.kqStartTime.slice(0,5)
						this.endWorkTime = this.dkInfo.kqEndTime.slice(0,5)
						if( this.dkInfo.beginTime ) {
							this.isBeginDk = true
							this.beginDkTime = this.dkInfo.beginTime.slice(-8,-3)
							this.isLate = this.dkInfo.late
						}else {
							this.timer = setInterval(()=> {
								this.getTodayDkInfo()
								clearInterval(this.timer)
							},500)
						}
						if( this.dkInfo.endTime.slice(-8) != '00:00:00' ) {
							this.isEndDk = true
							this.endDkTime = this.dkInfo.endTime.slice(-8,-3)
							this.isLeave = this.dkInfo.leave
						}
					}
				}
			}, 
			getSettingMess(){
				const _this = this;
				// 成功获取位置
				// 获取已授权类别
				uni.authorize({
					scope: 'scope.userLocation',
					// 成功
					success() {
						_this.startInterval()
					},
					// 失败
					fail() {
						// 1 用户拒绝授权
						// 2 用户之前拒绝了授权，此接口会直接进入失败回调
						//  以上两种情况都会进入到fail回调中
						// 一般搭配uni.getSetting和uni.openSetting使用

						// 官方文档中明确指出从2.3.0版本开始，当用户发生点击行为后才可以跳转打开设置页，不允许在用户无任何操作的情况下进行跳转
						// so报错 openSetting:fail can only be invoked by user TAP gesture.

						// 解决没办法 可通过提示框的按钮点击 触发opensetting
						//弹出框
						uni.showModal({
							title: '提示',
							content: '位置未授权，不可使用打卡功能，请重新授权定位权限',
							showCancel:true,
							success: function (res) {
								if(res.confirm){
									//打开设置
									uni.openSetting({
									  success(res) {
										let userLocation = res.authSetting['scope.userLocation'];
										if(userLocation){
											// 继续进行授权成功后的操作
											//用户开启位置权限
											uni.showToast({
												title: '定位已开启',
												duration: 2000
											});
										}else{
											// 用户拒接授权 给提示
											uni.showToast({
												title: '您已拒绝定位',
												duration: 2000,
												icon: "error"
											});
										}
									  }
									});
								}else{
									// 用户拒接授权 给提示
									uni.showToast({
										title: '您已拒绝定位',
										duration: 2000,
										icon: "error"
									});
									_this.distance = 99999
									if(Math.round(_this.distance) <= Number(_this.dkInfo.distance)){
									  _this.inRange = true
									}else {
									  _this.inRange = false
									}
								}
							}
						});
						
					}
				})
			},
			getWifi() {
				// 判断地址范围在多少之内可以
				const _this = this;
				uni.getLocation({
					type: 'wgs84',
					geocode: true,
					isHighAccuracy:true,
					success:(res) => {
						var result = gcoord.transform(
							[res.longitude, res.latitude],    // 经纬度坐标
							gcoord.WGS84,                 // 当前坐标系
							gcoord.GCJ02                   // 目标坐标系
						);
						// _this.info.cfPlace = res.address.city+res.address.district+res.address.poiName;
						_this.distance = getDistance(result[1], result[0],_this.dkInfo.latitude,_this.dkInfo.longitude)
					}
				});
			},
			// 上下班打卡
			punchIn(){
				if(!this.inRange){
					this.$refs.uToast.show({
					  type: 'default',
					  message: '未进入打卡范围'
					})
					return
				}
				
				if( this.xiabanTime ){
					const isDuanqi = compareTime(this.xiabanTime, this.nowTime, 'dkTime')
					if( isDuanqi == true ) {
						this.popupShow = false
					    this.renewTip = false
					    this.$refs.uToast.show({
						  type: 'default',
						  message: '15秒内不能再次打卡哦'
					  })
					  return
					}
				}
				
				// 查询用户上班点
				let dateTime = this.todayDate + " " + this.nowTime
				if( this.isBeginDk == false ) {
					// 上班打卡
					this.isLater = compareTime(this.dkInfo.kqStart.slice(-8), this.nowTime, 'sbDk')
					if( this.isLater == true ) {
						this.popupShow = true
					}else {
						this.editDk(this.dkInfoId, dateTime, this.dkInfo.endTime, this.lateOrEarlyRemark, 'sbDk')
					}
				} else {
					// 下班打卡
					this.isEarly = compareTime(this.nowTime, this.dkInfo.kqEnd.slice(-8), 'xbDk')
					if( this.isEarly == true ) {
						this.popupShow = true
					} else {
						this.editDk(this.dkInfoId, this.dkInfo.beginTime, dateTime, this.lateOrEarlyRemark, 'xbDk')
					}
				}
			},
			// 更新下班打卡
			renewEndTime() {
				if(!this.inRange){
					this.$refs.uToast.show({
					  type: 'default',
					  message: '未进入打卡范围'
					})
					return
				}
				if( this.xiabanTime ){
					const isDuanqi = compareTime(this.xiabanTime, this.nowTime, 'dkTime')
					if( isDuanqi == true ) {
						this.popupShow = false
					    this.renewTip = false
					    this.$refs.uToast.show({
						  type: 'default',
						  message: '15秒内不能再次打卡哦'
					  })
					  return
					}
				}
				this.renewTip = true
			},
			confirmDk(){
				let dateTime = this.todayDate + " " + this.nowTime
				if( this.isBeginDk == false ) {
					// 上班打卡
					this.editDk(this.dkInfoId, dateTime, this.dkInfo.endTime, this.lateOrEarlyRemark, 'sbDk')
				} else {
					// 下班打卡
					this.editDk(this.dkInfoId, this.dkInfo.beginTime, dateTime, this.lateOrEarlyRemark, 'xbDk')
				}
			},
			confirmRenew(type) {
				let dateTime = this.todayDate + " " + this.nowTime
				this.renewTip = false
				this.isEarly = compareTime(this.nowTime, this.dkInfo.kqEnd.slice(-8), 'xbDk')
				if( this.isEarly == true ) {
					this.popupShow = true
				} else {
					this.editDk(this.dkInfoId, this.dkInfo.beginTime, dateTime, this.lateOrEarlyRemark, 'xbDk', type)
				}
			},
			// 上下班打卡
			async editDk(id, sbDkTime, xbDkTime, remark, type, isRenew){
				let commitContent = {id:id, beginTime:sbDkTime, endTime:xbDkTime, remark:remark }
				this.xiabanTime = strFormatHourMSTime(xbDkTime)
				const { data } = await editDk(commitContent)
				if(data.code === 200) {
					this.popupShow = false
					if (type == 'sbDk') {
						this.isBeginDk = true
						this.dkInfo.beginTime = sbDkTime
						this.beginDkTime = sbDkTime.slice(-8,-3)
						this.isLater == true ? this.isLate = '1' : this.isLate = '0'
					} else {
						this.isEndDk = true
						this.dkInfo.endTime = xbDkTime
						this.endDkTime = xbDkTime.slice(-8, -3)
						this.isEarly == true ? this.isLeave = '1' : this.isLeave = '0'
						if(isRenew == 'renew') {
							this.$refs.uToast.show({
								type: 'success',
								message: '下班更新打卡成功'
							})
						}
					}
					let time = setTimeout(item => {
						this.showDkSuc = true
						clearTimeout(time)      
					}, 500)
					this.startMP3()
				}
				this.closeDkSucAuto()
			},
			startMP3() {
				const innerAudioContext = uni.createInnerAudioContext();
				innerAudioContext.autoplay = true;
				innerAudioContext.src = 'https://www.zxsl.zxmap.cn/zxch-app/2023/05/09/be646e18316f42548f1333bd058f03fd.mp3';
				innerAudioContext.onPlay(() => {console.log('成功播放')});
			},
			closeDkSucAuto(){
				//设置五秒后弹窗自动关闭
				let time = setTimeout(item => {
					this.showDkSuc = false;
					clearTimeout(time)      
				}, 3000)
			},
			isShowSuc(index){
				this.showDkSuc = index
			},
			// 关闭更新提示
			closeRenewTip() {
				this.renewTip = false
			},
			clickTab(e) {
				if(e == 0 ){
					this.startInterval()
				}else if(e == 1){
					this.closeInterval()
				}
				this.tabValue = e
			},
			//打开定时器
			startInterval() {
				var that = this
				this.timeout = setInterval(function () {
					var now = new Date();
					var hour = now.getHours();//得到小时
					var minu = now.getMinutes();//得到分钟
					var sec = now.getSeconds();//得到秒
					　var MS = now.getMilliseconds();//获取毫秒
					if (hour < 10) hour = "0" + hour;
					if (minu < 10) minu = "0" + minu;
					if (sec < 10) sec = "0" + sec;
					var time = "";
					that.nowTime = hour + ":" + minu + ":" + sec;
					// 获取手机wifi信息
					if(that.locationCount == 3){
						that.getWifi()
						that.locationCount = 0
					console.log('高德定位接口')
					}
					that.locationCount += 1
					// if(user.macs.indexOf(that.bssid) > -1){
					 //  that.inRange = true
					// }
				if(Math.round(that.distance) <= Number(that.dkInfo.distance)){
					  that.inRange = true
					}else {
					  that.inRange = false
					}
				},1000);
			},
			//清空定时器，即停止定时器
			closeInterval() {
				clearInterval(this.timeout);
				clearInterval(this.timer)
			},
			closeTimeOut() {
				this.showCloseTime = false
				clearInterval(this.timeout);
				uni.navigateBack()
			}
		}
	}
</script>

<style lang="scss">
@import "./index.scss";

.circle{ 
	margin-top: 200rpx;
	// position: relative;
	&-body{
		width: 250rpx;
		height: 250rpx; 
		background-color: #0089FF;
		border-radius: 50%; 
		margin: auto;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		// padding:95rpx 0;
		// position: absolute;
		// top: 35%;
		// margin-left: 26%;
		text-align: center;
		// justify-content: center;
		&-title {
		  font-size: 35rpx;
		  // letter-spacing: 0rpx;
		  color: #ffffff;
		}
		&__content {
		  font-size: 28rpx;
		  color: #d6d6d6;
		}
	}
	&-content {
		font-size: 28rpx;
		margin-left: 6rpx;
	}
}

.slot-content {
	display: flex;
	align-items: center;
	flex: 1;
	justify-content: center;
	&__text {
		margin-left: 10rpx;
	}
}
</style>
